//活动列表表格
var $customerProductActivityTable = $('#customerProductActivityTableList');

//初始化活动列表页面
$(function () {
    // 时间范围
    $('#activityDate').daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(24, 'hour'),
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            cancelLabel: '清空'
        },
        timePicker24Hour : true,
        autoUpdateInput: false,
    });
    $('#activityDate').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD HH:mm') + ' 至 ' + picker.endDate.format('YYYY-MM-DD HH:mm'));
    });
    $('#activityDate').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });

    customerProductActivityTableListInit();//初始化活动列表
});

/**
 * 初始化活动列表
 */
function customerProductActivityTableListInit(){
    //先销毁表格
    $customerProductActivityTable.bootstrapTable('destroy');
    $customerProductActivityTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/customerProductActivity/selectCustomerProductActivityList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productActivityId',
        idField: 'productActivityId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'productActivityId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', formatter: indexFormat},
            {title: '活动名称',field: 'productActivityName',align: 'left', valign: 'middle'},
            {title: '活动开始日期', field: 'activityPeriodValidityStart',align: 'left', valign: 'middle'},
            {title: '活动结束日期', field: 'activityPeriodValidityEnd',align: 'left', valign: 'middle'},
            {title: '活动价格', field: 'activityPrice',align: 'left', valign: 'middle'},
            {title: '兑换方式', field: 'exchangeMethod', align: 'left',valign: 'middle'},
            {title: '创建人', field: 'createPeopleName',align: 'left',valign: 'middle'},
            {title: '创建时间', field: 'createTm',align: 'left',valign: 'middle'},
            {title: '操作',field:'operate',align:'left',events:operateEvents,formatter: genderOpt,width:'10%'},
            {title: '是否上架',field:'activityShelfStatus',align:'right',formatter: operateActivityShelfStatusFormat,width:'5%'}
        ],
        responseHandler: function (result) {
            if(result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
            // table操作列下拉菜单效果
            tableNav();
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 拼接活动列表查询条件参数
 */
function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式

    //活动列表搜索条件
    params.productActivityName = $.trim($('#productActivityName').val());//活动名称
    if($('#activityDate').val()){
        var activityDate = $('#activityDate').val().split(" 至 ");//活动时间
        if(activityDate.length > 0){
            var activityPeriodValidityStart = activityDate[0];
            var activityPeriodValidityEnd = activityDate[1];
            params.activityPeriodValidityStart = activityPeriodValidityStart;//活动开始日期
            params.activityPeriodValidityEnd = activityPeriodValidityEnd;//活动结束日期
        }
    }
    return params;
}

//活动列表--按查询条件搜索
function searchProductActivityTable(){
    $customerProductActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 活动列表--列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 *活动列表--自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button class="btn btn-default" id="detail"><i class="mdi mdi-eye"></i>查看</button>';
    html += '<div class="dropdown"><button class="btn btn-link" data-index="' + index + '"><i class="mdi mdi-dots-vertical"></i></button><ul class="dropdown-menu">';
    html += '<li><a class="js-create-tab" data-title="编辑活动" data-url="/front/activityManager/editProductActivity?activityId=' + row.productActivityId+'" >编辑</a></li>';
    html += '</ul></div>';
    return html;
}

/**
 *活动列表--自定义操作列事件
 */
window.operateEvents = {
    // 查看活动
    'click #detail': function(e, value, row, index) {
        $("#detailContent").modal('show');
        showActivityProductInfo(row);//展示活动及产品信息
    }
};

/**
 *查询活动产品信息
 * @param row
 */
function showActivityProductInfo(row){
    $.ajax({
        type: "post",
        url: "/customerProductActivity/selectCustomerProductActivityById",
        data: {
            productActivityId:  row.productActivityId
        },
        dataType: 'json',
        async: false,
        success: function (data, status) {
            if(data.code == '000000') {
                if(data.code == '000000') {
                    var data = data.data;
                    $('#activityNamePop').text(data.productActivityName);//活动名称
                    $("#activityPeriodValidityStart").text(data.activityPeriodValidityStart);//活动开始时间
                    $("#activityPeriodValidityEnd").text(data.activityPeriodValidityEnd);//活动结束时间
                    $("#startPrice").text(data.activityPriceRangeStart);//活动价格区间起始价
                    $("#endPrice").text(data.activityPriceRangeEnd);//活动价格区间截止价
                    $("#activityPrice").text(data.activityPrice);//活动价
                    $("#exchangeMethod").text(exchangeMethodFormat(data.exchangeMethod));
                    //产品信息
                    var customerProductList = data.customerProductList;
                    $('#relateProductList').html('');
                    var tempHtml = '';
                    customerProductList.map(function(item, index) {
                        tempHtml += ' <div class="list" style="display: flex">\n' +
                            '                        <div class="lable-pop">相关产品：</div>\n' +
                            '                        <div id="relateProduct" style="margin-right: 10%">'+item.productName+'</div>\n' +
                            '                        <div class="lable-pop">价格：</div>\n' +
                            '                        <div id="relateNum">'+item.productFinalPrice+'</div>\n' +
                            '                    </div>'
                    });
                    $('#relateProductList').append(tempHtml);
                }
            }
        },
        error:function(){
            $.alert("操作失败,请稍后再试!");
        }
    });
}

//兑换方式格式化
function exchangeMethodFormat(exchangeMethod){
    if (exchangeMethod == null || exchangeMethod == undefined) {
        return "";
    }else if(exchangeMethod == 1){
        return "电子卡";
    }else if(exchangeMethod == 2){
        return "兑换码";
    }else if(exchangeMethod == 3){
        return "学习码";
    }else if(exchangeMethod == 4){
        return "充值码";
    }else if(exchangeMethod == 5){
        return "税法直通车学习卡";
    }else if(exchangeMethod == 6){
        return "其他";
    }else{
        return "";
    }
}

/**
 * 活动上/下架列显示
 */
function operateActivityShelfStatusFormat(value, row, index){
    var is_checked = '';
    let shelfStatus = '';
    var newShelfStatus;
    if(value == null || value == undefined) {
        return '';
    }else if(value == 0) {
        is_checked = 'checked="checked"';
        newShelfStatus = 1;
    } else if (value == 1) {
        is_checked = '';
        newShelfStatus = 0;
    }
    var shelfStatusHtml = '<label class="lyear-switch switch-solid switch-success">' +
        '<input type="checkbox" id="shelfStatus' + row.productActivityId  + '" ' + is_checked + '>' +
        '<span onClick="updateActivityShelfStatus(\'' + row.productActivityId + '\', \'' + newShelfStatus + '\')"></span>' +
        '</label>';
    return shelfStatusHtml;
}

/**
 * 活动上/下架操作
 */
function updateActivityShelfStatus(productActivityId,shelfStatus){
    var confirmMessage = '';
    if (shelfStatus == 0) {
        //判断是否在活动有效期内
        $.ajax({
            type: "post",
            url: "/customerProductActivity/selectActivityIsInValidityPeriod",
            data: {
                productActivityId: productActivityId
            },
            dataType: 'json',
            async: false,
            success: function (data, status) {
                if(data.code == '000000') {
                    confirmMessage = "确定上架吗？";
                    sendUpdateActivityShelfStatus(productActivityId,shelfStatus,confirmMessage);
                }else{
                    $.alert("活动已结束不能上架");
                    $("#shelfStatus" + productActivityId).prop('checked',true);
                }
            },
            error:function(){
                $.alert("操作失败,请稍后再试!");
            }
        });
    } else {
        confirmMessage = "确定下架吗？";
        sendUpdateActivityShelfStatus(productActivityId,shelfStatus,confirmMessage);
    }
}

/**
 * 活动上/下架调用后端接口
 */
function sendUpdateActivityShelfStatus(productActivityId,shelfStatus,confirmMessage){
    $.alert({
        title: '提示',
        content: confirmMessage,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerProductActivity/updateActivityShelfStatus",
                        data: {
                            productActivityId: productActivityId,//活动ID
                            activityShelfStatus: shelfStatus//上/下架状态
                        },
                        dataType: 'json',
                        success: function (data, status) {
                            if (data.code == '000000') {
                                $customerProductActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            } else {
                                $.alert(data.message);
                                $customerProductActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                            }
                        },
                        error: function () {
                            $.alert('修改失败，请稍后再试!');
                            $customerProductActivityTable.bootstrapTable('refreshOptions', {pageNumber: 1});
                        }
                    });
                }
            },
            cancel: {
                text: '取消',
                action: function () {
                    if(shelfStatus == 1){//原先是上架状态
                        $("#shelfStatus" + productActivityId).prop('checked',true);
                    }else {
                        $("#shelfStatus" + productActivityId).prop('checked',false);
                    }
                }
            }
        }
    });
}

/**
 * 新增活动
 */
function addCustomerProductActivity(){
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '新增活动',
        url : "/front/activityManager/addProductActivity"
    }, true)
}



